package com.controller;

import com.entity.Users;
import com.entity.table.UsersTableDef;
import com.service.UsersService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class LoginController {

    @Autowired
    UsersService usersService;

    @GetMapping("/login")
    public String toLoginPage(){
        return "client/login";
    }
    //提交登录
    @PostMapping("/toLogin")
    public String login(Users user, HttpSession httpSession, Model model){
        Users users =  usersService.queryChain().where(UsersTableDef.USERS.USERNAME.eq(user.getUsername()))
                .and(UsersTableDef.USERS.PASSWORD.eq(user.getPassword())).one();
        if (users!=null){
            // 将用户对象添加到Session
            httpSession.setAttribute("user", users);
            model.addAttribute("user", users);//返回数据给前端页面
            // 跳转到主页面
            return "redirect:/";//登录成功跳转到首页链接
              //return "client/index";//静态页面
        }
        else {
            model.addAttribute("msg", "账号或密码错误，请重新输入！");
            return "client/login";
        }
    }
}
